/**
* 投票活动列表页面
* 功能：
* 1. 显示投票活动列表，支持搜索和筛选
* 2. 固定头部搜索栏和筛选标签
* 3. 卡片式展示投票活动信息
* 4. 支持投票操作和页面跳转
* 5. 包含加载状态和空状态处理
*/
<template>
    <view class="page-container">
        <!-- 页面头部 -->
        <page-header title="投票活动" @heightChange="handleHeaderHeightChange($event)" />

        <!-- 固定搜索栏 -->
        <view class="header-search-section" :style="{ top: headerHeight + 'px' }">
            <view class="search-input-box">
                <uni-icons type="search" size="18" color="#999"></uni-icons>
                <input class="search-input-field" placeholder="搜索投票活动" v-model="searchKeyword"
                    @input="handleSearchInput()" />
                <uni-icons v-if="searchKeyword" type="clear" size="18" color="#999" @click="clearSearch()"></uni-icons>
            </view>
        </view>

        <!-- 固定筛选标签 -->
        <view class="header-filter-section" :style="{ top: (headerHeight + 48) + 'px' }">
            <scroll-view class="filter-scroll-view" scroll-x="true" show-scrollbar="false">
                <view class="filter-tabs-container">
                    <view class="filter-tab-item" :class="{ active: currentFilter === item.value }"
                        v-for="item in filterTabs" :key="item.value" @click="handleFilterClick(item.value)">
                        <view class="tab-label-text">{{ item.label }}</view>
                        <view class="tab-count-text" v-if="item.count">({{ item.count }})</view>
                    </view>
                </view>
            </scroll-view>
        </view>

        <!-- 活动列表 -->
        <view class="content-vote-list">
            <view class="vote-list-item" v-for="item in filteredVoteList" :key="item.id" @click="handleVoteClick(item)">
                <!-- 上方区域：图片和标题简述左右排列 -->
                <view class="vote-top-section">
                    <!-- 活动图片 -->
                    <view class="vote-image-container">
                        <image :src="item.image" mode="aspectFill" />
                        <view class="vote-status-tag-item" :class="item.status">
                            <view class="status-text">{{ handleGetStatusText(item.status) }}</view>
                        </view>
                    </view>

                    <!-- 活动标题和描述 -->
                    <view class="vote-title-desc-container">
                        <view class="vote-title-text">
                            <view class="title-text">{{ item.title }}</view>
                        </view>
                        <view class="vote-desc-text">
                            <view class="desc-text">{{ item.description }}</view>
                        </view>
                    </view>
                </view>

                <!-- 中间区域：进度条作为分割线 -->
                <view class="vote-progress-section">
                    <view class="vote-progress-container">
                        <view class="progress-bar-container">
                            <view class="progress-fill-bar" :style="{ width: item.progress + '%' }"></view>
                        </view>
                        <view class="progress-text-label">{{ item.progress }}%</view>
                    </view>
                </view>

                <!-- 下方区域：人数日期票数和按钮左右排列 -->
                <view class="vote-bottom-section">
                    <!-- 活动数据 -->
                    <view class="vote-stats-container">
                        <view class="stat-item-container">
                            <uni-icons type="person" size="12" color="#999"></uni-icons>
                            <view class="stat-text">{{ item.participants }}人</view>
                        </view>
                        <view class="stat-item-container">
                            <uni-icons type="calendar" size="12" color="#999"></uni-icons>
                            <view class="stat-text">{{ item.endTime }}</view>
                        </view>
                        <view class="stat-item-container">
                            <uni-icons type="star" size="12" color="#999"></uni-icons>
                            <view class="stat-text">{{ item.voteCount }}票</view>
                        </view>
                    </view>

                    <!-- 操作按钮 -->
                    <view class="vote-action-container">
                        <button class="vote-btn-item" :class="{ disabled: item.status === 'ended' }"
                            @click.stop="handleVoteAction(item)">
                            {{ handleGetActionText(item.status) }}
                        </button>
                    </view>
                </view>
            </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-state-container" v-if="filteredVoteList.length === 0">
            <image class="empty-image-item" src="/static/empty.png" mode="aspectFit" />
            <view class="empty-text-label">暂无投票活动</view>
            <view class="empty-desc-label">稍后再来看看吧</view>
        </view>

        <!-- 加载框 -->
        <uni-popup ref="loadingPopup" type="center" :mask-click="false" @change="handlePopupChange($event)">
            <view class="loading-content-container">
                <image class="loading-image-item" src="/static/image/loading.png" mode="aspectFit" />
                <view class="loading-text-label">{{ loadingText }}</view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
// 结构
import {
    defineComponent,
    onMounted,
    ref,
    computed,
    watch
} from 'vue';
import { onPullDownRefresh } from '@dcloudio/uni-app';
// 模块化
import PageHeader from '@/components/PageHeader.vue';
import { storage } from '@/library/storage.js';

export default defineComponent({
    name: 'VoteList',
    props: {
        // 接收父组件数据
    },
    components: {
        PageHeader
    },
    setup(props, ctx) {
        // ===== 响应式对象 =====
        // 头部高度
        const headerHeight = ref(64);
        // 搜索相关
        const searchKeyword = ref('');
        // 筛选相关
        const currentFilter = ref('all');
        const filterTabs = ref([
            { label: '全部', value: 'all', count: 0 },
            { label: '进行中', value: 'ongoing', count: 0 },
            { label: '即将截止', value: 'ending', count: 0 },
            { label: '已结束', value: 'ended', count: 0 }
        ]);
        // 投票列表数据
        const voteList = ref([
            {
                id: 1,
                title: '2024年度最佳员工评选',
                description: '评选年度表现最优秀的员工，表彰先进，激励团队',
                image: '/static/example.png',
                participants: 256,
                endTime: '2024-03-31',
                status: 'ongoing',
                voteCount: 1234,
                progress: 85
            },
            {
                id: 2,
                title: '新产品功能投票',
                description: '为我们的新产品功能提出您的建议和想法',
                image: '/static/example.png',
                participants: 189,
                endTime: '2024-03-25',
                status: 'ongoing',
                voteCount: 856,
                progress: 62
            },
            {
                id: 3,
                title: '年度团建活动方案',
                description: '选择您最期待的团建活动方案',
                image: '/static/example.png',
                participants: 312,
                endTime: '2024-03-20',
                status: 'ending',
                voteCount: 2341,
                progress: 95
            },
            {
                id: 4,
                title: '企业文化标语征集',
                description: '征集企业文化标语，展现企业精神',
                image: '/static/example.png',
                participants: 156,
                endTime: '2024-03-15',
                status: 'ended',
                voteCount: 567,
                progress: 100
            }
        ]);
        // 加载相关
        const loadingText = ref('加载中...');
        const loadingPopup = ref(null);
        const isPopupVisible = ref(false);
        // 底部安全区高度
        const bottomSafeHeight = ref(0);

        // ===== 计算属性 =====
        // 过滤后的投票列表
        const filteredVoteList = computed(() => {
            let filtered = voteList.value;

            // 按状态筛选
            if (currentFilter.value !== 'all') {
                filtered = filtered.filter(item => item.status === currentFilter.value);
            }

            // 按关键词搜索
            if (searchKeyword.value) {
                const keyword = searchKeyword.value.toLowerCase();
                filtered = filtered.filter(item =>
                    item.title.toLowerCase().includes(keyword) ||
                    item.description.toLowerCase().includes(keyword)
                );
            }

            return filtered;
        });

        // ===== 监听器 =====
        // 监听搜索关键词变化
        watch(searchKeyword, (newValue) => {
            // 实时搜索处理
        });

        // ===== 交互方法 =====
        // 处理头部高度变化
        const handleHeaderHeightChange = (heightInfo) => {
            headerHeight.value = heightInfo?.totalHeaderHeight || 64;
        };

        // 搜索输入处理
        const handleSearchInput = () => {
            // 实时搜索，这里可以添加防抖
        };

        // 清除搜索
        const clearSearch = () => {
            searchKeyword.value = '';
        };

        // 筛选点击
        const handleFilterClick = (filterValue) => {
            currentFilter.value = filterValue;
        };

        // 投票点击
        const handleVoteClick = (item) => {
            uni.navigateTo({
                url: `/pages-vote/vote/VoteDetail?id=${item.id}`
            });
        };

        // 投票操作
        const handleVoteAction = (item) => {
            if (item.status === 'ended') {
                uni.showToast({
                    title: '活动已结束',
                    icon: 'none'
                });
                return;
            }

            uni.navigateTo({
                url: `/pages-vote/vote/VoteDetail?id=${item.id}`
            });
        };

        // 监听popup状态变化
        const handlePopupChange = (e) => {
            console.log('handlePopupChange', e);
            isPopupVisible.value = e.show;
        };

        // 获取状态文本
        const handleGetStatusText = (status) => {
            const statusMap = {
                ongoing: '进行中',
                ending: '即将截止',
                ended: '已结束'
            };
            return statusMap[status] || '未知';
        };

        // 获取操作文本
        const handleGetActionText = (status) => {
            const actionMap = {
                ongoing: '立即投票',
                ending: '立即投票',
                ended: '查看结果'
            };
            return actionMap[status] || '查看详情';
        };

        // 初始化底部安全区高度
        const initBottomSafeHeight = () => {
            const deviceInfo = storage.getDeviceInfo();
            bottomSafeHeight.value = deviceInfo?.ui?.bottomSafeHeight || 10;
        };

        // 加载投票数据
        const loadVoteData = async () => {
            loadingText.value = '加载投票数据...';
            loadingPopup.value.open();

            try {
                // 模拟加载延迟
                setTimeout(() => {
                    // 更新筛选标签数量
                    updateFilterCounts();
                    loadingPopup.value.close();
                }, 500);
            } catch (error) {
                console.error('加载投票数据失败:', error);
                uni.showToast({
                    title: '加载数据失败',
                    icon: 'none'
                });
                loadingPopup.value.close();
            }
        };

        // 更新筛选标签数量
        const updateFilterCounts = () => {
            const counts = {
                all: voteList.value.length,
                ongoing: voteList.value.filter(item => item.status === 'ongoing').length,
                ending: voteList.value.filter(item => item.status === 'ending').length,
                ended: voteList.value.filter(item => item.status === 'ended').length
            };

            filterTabs.value.forEach(tab => {
                tab.count = counts[tab.value];
            });
        };

        // ===== 生命周期钩子 =====
        onMounted(() => {
            initBottomSafeHeight();
            loadVoteData();
        });

        // 下拉刷新
        onPullDownRefresh(() => {
            loadVoteData();
            setTimeout(() => {
                uni.stopPullDownRefresh();
            }, 100);
        });

        // ===== 返回数据和方法 =====
        return {
            // 响应式对象
            headerHeight,
            bottomSafeHeight,
            searchKeyword,
            currentFilter,
            filterTabs,
            loadingText,
            loadingPopup,
            isPopupVisible,
            voteList,
            filteredVoteList,

            // 交互方法
            handleHeaderHeightChange,
            handleSearchInput,
            clearSearch,
            handleFilterClick,
            handleVoteClick,
            handleVoteAction,
            handlePopupChange,
            handleGetStatusText,
            handleGetActionText,
            loadVoteData
        };
    }
});
</script>

<style lang='less' scoped>
/* 页面根容器样式 */
.page-container {
    width: 100%;
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-top: v-bind('headerHeight + 96 + "px"');
    /* 头部高度 + 搜索栏高度(48px) + 筛选标签高度(48px) */
    padding-bottom: v-bind('bottomSafeHeight + "px"');
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;

    // 页面头部（PageHeader）无额外样式

    .header-search-section {
        position: fixed;
        left: 0;
        right: 0;
        z-index: 99;
        background-color: #ffffff;
        border-bottom: 1rpx solid #f0f0f0;
        padding: 8rpx 20rpx 8rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
        height: 48px;
        box-sizing: border-box;

        .search-input-box {
            display: flex;
            align-items: center;
            background-color: #f8f8f8;
            border-radius: 24rpx;
            padding: 12rpx 24rpx;
            height: 32px;
            box-sizing: border-box;

            .search-input-field {
                flex: 1;
                margin-left: 16rpx;
                font-size: 28rpx;
                color: #333;
                height: 100%;
                line-height: 32px;
            }
        }
    }

    .header-filter-section {
        position: fixed;
        left: 0;
        right: 0;
        z-index: 98;
        background-color: #ffffff;
        border-bottom: 1rpx solid #f0f0f0;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
        height: 48px;
        box-sizing: border-box;

        .filter-scroll-view {
            white-space: nowrap;
            padding: 0 20rpx;
            height: 100%;
        }

        .filter-tabs-container {
            display: flex;
            padding: 8rpx 0;
            height: 100%;
            align-items: center;

            .filter-tab-item {
                display: flex;
                align-items: center;
                padding: 8rpx 20rpx;
                margin-right: 16rpx;
                background-color: #f8f8f8;
                border-radius: 20rpx;
                font-size: 26rpx;
                color: #666;
                transition: all 0.3s;
                height: 32px;
                box-sizing: border-box;

                &.active {
                    background-color: #007AFF;
                    color: #ffffff;
                }

                .tab-label-text {}

                .tab-count-text {
                    margin-left: 6rpx;
                    font-size: 22rpx;
                    opacity: 0.8;
                }
            }
        }
    }

    .content-vote-list {
        padding: 20rpx;

        .vote-list-item {
            background-color: #ffffff;
            border-radius: 16rpx;
            margin-bottom: 20rpx;
            overflow: hidden;
            box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
            display: flex;
            flex-direction: column;
            /* Changed to column for top-bottom layout */
            padding: 0;

            .vote-top-section {
                display: flex;
                align-items: flex-start;
                padding: 24rpx 20rpx 16rpx;
                gap: 20rpx;
            }

            .vote-image-container {
                position: relative;
                width: 140rpx;
                height: 140rpx;
                flex-shrink: 0;
                margin-right: 0;

                image {
                    width: 100%;
                    height: 100%;
                    border-radius: 12rpx;
                    object-fit: cover;
                }

                .vote-status-tag-item {
                    position: absolute;
                    top: 8rpx;
                    right: 8rpx;
                    padding: 4rpx 8rpx;
                    border-radius: 12rpx;
                    font-size: 20rpx;

                    &.ongoing {
                        background-color: #e6f7ff;
                        color: #007AFF;
                    }

                    &.ending {
                        background-color: #fff7e6;
                        color: #ff9500;
                    }

                    &.ended {
                        background-color: #f5f5f5;
                        color: #999;
                    }

                    .status-text {}
                }
            }

            .vote-title-desc-container {
                flex: 1;
                min-width: 0;
                display: flex;
                flex-direction: column;
                justify-content: flex-start;
                padding-right: 0;

                .vote-title-text {
                    font-size: 30rpx;
                    font-weight: bold;
                    color: #333;
                    margin-bottom: 8rpx;
                    line-height: 1.3;

                    .title-text {
                        display: -webkit-box;
                        -webkit-box-orient: vertical;
                        -webkit-line-clamp: 2;
                        overflow: hidden;
                    }
                }

                .vote-desc-text {
                    font-size: 26rpx;
                    color: #666;
                    line-height: 1.4;
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 2;
                    overflow: hidden;

                    .desc-text {}
                }
            }

            .vote-progress-section {
                padding: 0 20rpx 16rpx;

                .vote-progress-container {
                    .progress-bar-container {
                        height: 6rpx;
                        background-color: #f0f0f0;
                        border-radius: 3rpx;
                        overflow: hidden;
                        margin-bottom: 8rpx;

                        .progress-fill-bar {
                            height: 100%;
                            background-color: #007AFF;
                            border-radius: 3rpx;
                            transition: width 0.3s;
                        }
                    }

                    .progress-text-label {
                        font-size: 22rpx;
                        color: #999;
                    }
                }
            }

            .vote-bottom-section {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 0 20rpx 24rpx;

                .vote-stats-container {
                    display: flex;
                    gap: 24rpx;
                    font-size: 24rpx;
                    color: #999;

                    .stat-item-container {
                        display: flex;
                        align-items: center;

                        .stat-text {
                            margin-left: 6rpx;
                        }
                    }
                }

                .vote-action-container {
                    flex-shrink: 0;
                    display: flex;
                    align-items: center;

                    .vote-btn-item {
                        width: fit-content;
                        height: 60rpx;
                        background-color: #007AFF;
                        color: #ffffff;
                        border-radius: 30rpx;
                        font-size: 24rpx;
                        font-weight: bold;
                        border: none;
                        transition: all 0.3s;
                        display: flex;
                        align-items: center;
                        justify-content: center;

                        &.disabled {
                            background-color: #f5f5f5;
                            color: #999;
                        }

                        &:active {
                            transform: scale(0.98);
                        }
                    }
                }
            }
        }
    }

    .empty-state-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 100rpx 40rpx;
        text-align: center;

        .empty-image-item {
            width: 200rpx;
            height: 200rpx;
            margin-bottom: 40rpx;
            opacity: 0.5;
        }

        .empty-text-label {
            font-size: 32rpx;
            color: #999;
            margin-bottom: 16rpx;
        }

        .empty-desc-label {
            font-size: 28rpx;
            color: #ccc;
        }
    }

    .loading-content-container {
        background-color: rgba(0, 0, 0, 0.8);
        border-radius: 16rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 40rpx;
        height: 200rpx;
        width: 200rpx;
        overflow: hidden;
        justify-content: center;
        align-items: center;

        .loading-image-item {
            width: 120rpx;
            height: 120rpx;
            margin-bottom: 20rpx;
            animation: rotate 1s linear infinite;
        }

        .loading-text-label {
            margin-top: 10rpx;
            color: #ffffff;
            font-size: 30rpx;
            text-align: center;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
            word-break: break-all;
        }
    }
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}
</style>